package com.shenghua.utils.sysutil;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;

/**
 * Created by Administrator on 2019/4/28.
 */
public class BeanUtils {
    private static ApplicationContext context;

    static {
        context = ContextLoader.getCurrentWebApplicationContext();
    }

    public static synchronized ApplicationContext getContext() {
        if(null == context) {
            context = ContextLoader.getCurrentWebApplicationContext();
        }
        return context;
    }

    public static <T>T getBean(Class<T> tClass) {
        return getContext().getBean(tClass);
    }

    public Class getClass(HttpServletRequest request, String clsName) {
        BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        Object object = beanFactory.getBean(clsName);
        return object.getClass();
    }

    public static <T> BeanInfo getBeanInfo(Class<T> tClass) {
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(tClass);
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return  beanInfo;
    }

}
